//
//  BRSettingViewController.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/9/29.
//  Copyright © 2021 Brezze GWG. All rights reserved.
//

#import "BRSettingViewController.h"
#import "BRTopTitleTableViewCell.h"
#import "BRAlertCustomView.h"
#import "AppDelegate.h"
#import "GXJWebViewController.h"
#import "BRTitleTableViewCell.h"
#import "BRMFaceLoginSwitchCell.h"
#import "BRCancellationViewController.h"

@interface BRSettingViewController ()<QMUITableViewDelegate,QMUITableViewDataSource>
{
    
}
@property (nonatomic,strong) NSArray *lists;

// faceId swicth
@property (nonatomic,assign) BOOL isSwitch;

@property (nonatomic,assign) BOOL isFaceLock;

@end

@implementation BRSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    // 检测
    [GGFaceIdManManage gg_checkFaceAction:^{

    } faile:^(NSInteger code) {

        if (@available(iOS 11.0, *)) {
            if (code == LAErrorBiometryLockout) {
                self.isFaceLock = YES;

            }
        }
    }];

    self.isSwitch = [GGFaceIdManManage gg_checkIsEqual];
    [self.tableView reloadData];
}

- (void)openFaceLogin:(BOOL)isOn {
    if (self.isFaceLock) {
        // 如果被锁定
        self.isSwitch = NO;
        [self.tableView reloadData];
        [BRHud showAuto:Localized(@"Set_biometry_locked") inView:self.view];
        return;
    }
    self.isSwitch = isOn;
    if (!isOn) {
        
        // 关闭face
        [self requestToDelete];
        return;
    }
    
    WS(weakSelf);
    [GGFaceIdManManage gg_runFaceAction:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf requestToSave];
        });
    } faile:^(NSInteger code) {
        weakSelf.isSwitch = NO;
        if (@available(iOS 11.0, *)) {
            if (code == LAErrorBiometryLockout) {
                weakSelf.isFaceLock = YES;

            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableView reloadData];
        });
        
    }];
}

- (void)requestToSave {
    [BRHud showInView:self.view];
    //[BRAPI faceIDSave]
    [[BRRequestManager shared] POST:[BRAPI faceIDSave] params:@{@"state":@(1),@"token":USERManager.token} succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        [BRHud hiddenInView:self.view];
        [BRHud showAuto:Localized(@"public_success") inView:self.view];
        [GGFaceIdManManage gg_saveData];
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        self.isSwitch = NO;
        
        [BRHud hiddenInView:self.view];
        [self.tableView reloadData];
    }];
}

- (void)requestToDelete {
    
    NSString *token = [GGFaceIdManManage gg_token];
    //[BRAPI faceIDDelete]
    [[BRRequestManager shared] POST:[BRAPI faceIDSave] params:@{@"state":@(0),@"token":token} succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        
        
    }];
    [GGFaceIdManManage  gg_removeCache];
}

- (void)request:(NSString *)la {
    // 接口已废弃，注释掉
    /*
    [[BRRequestManager shared] PUT:[BRAPI languageSwitch:la] params:nil succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        
    }];
    */
}

- (void)logout {
    BRCustiomAlertView *alertV = [[BRCustiomAlertView alloc] initWithTitle:Localized(@"set_logout") subTitle:Localized(@"set_comfirmLogout") cancelStr:Localized(@"public_cancel") succStr:Localized(@"public_confirm") cancelAction:^{
        NSLog(@"取消");
        
    } successAction:^{
        NSLog(@"确定");
        [self logoutSucc];
    } showBC:YES];
  
    
    
    [self.view addSubview:alertV];
}

- (void)logoutSucc {
    [[BRUserManager share] logout:^{
        AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [app didInitWindow];
    } faile:^{
        AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [app didInitWindow];
    }];
}

- (void)policyClick:(NSInteger)type {
    [self.view endEditing:YES];
    // 使用新的协议URL生成方法，根据当前语言动态生成
    NSString *url = [BRTools br_agreementURLWithType:type];
    NSString *titleStr = Localized(@"set_terms");
    if (type == 1) {
        titleStr = Localized(@"set_privacy");
    }
    GXJWebViewController *webView = [[GXJWebViewController alloc] init];
    webView.url = url ;
    [webView initWhiteBarWithTitle:titleStr isBack: YES];
    webView.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:webView animated:YES completion:nil];
}

#pragma mark - tableView Delegate --
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  
    return 60;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.lists.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *title = self.lists[indexPath.row];
    if ([title isEqualToString:Localized(@"set_biometryLogin")]) {
        
        BRMFaceLoginSwitchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BRMFaceLoginSwitchCell"];

        if (!cell) {
            cell = [[BRMFaceLoginSwitchCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BRMFaceLoginSwitchCell"];
        }
        cell.isOn = self.isSwitch;
        
        WS(weakSelf);
        cell.switchBlock = ^(BOOL isOn) {
            [weakSelf openFaceLogin:isOn];
        };
        
        return cell;
    }
    BRTitleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BRTitleTableViewCell"];
//    cell.stackX.constant = 28;
    cell.titleL.text = title;
    cell.hasText = indexPath.row <= 1;
    cell.hasRImg = indexPath.row != 1;
    
    if ([title isEqualToString:Localized(@"set_selectLanguage")]) {
        cell.textL.text = [[BRLanguageManager share] describe];
        
    }
    if ([title isEqualToString:Localized(@"menu_version")]) {
        cell.textL.text = [NSString stringWithFormat:@"V %@",[BRTools getAppVersion]];
    }

    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    [self didSelectWithTitle:self.lists[indexPath.row]];
}

- (void)didSelectWithTitle:(NSString *)title {
    
    if ([title isEqualToString:Localized(@"menu_version")]) {
        
        return;
    }
    
    if ([title isEqualToString:Localized(@"set_selectLanguage")]) {
        
        BRAlertCustomView *alert = [[BRAlertCustomView alloc] initWithFrame:self.view.bounds type:1];
        alert.contentView.layer.cornerRadius = 28;
        alert.titleStr = Localized(@"set_selectLanguage");
        alert.listArr = [[BRLanguageManager share] languageDescribes];
        [alert setRightBtnTitle:Localized(@"home_confirm")];
        [self.view addSubview:alert];
        [alert selectStr:[[BRLanguageManager share] describe]];
        WS(weakSelf);
        alert.alertBlock = ^(NSString * _Nonnull changeText, NSInteger index, void (^ _Nonnull hidd)(BOOL)) {
            
            NSArray *laArr  = [[BRLanguageManager share] languages];
            if (index >= laArr.count) hidd(NO);
            BRLanguageModel *model = laArr[index];
            [[BRLanguageManager share] setNewLanguage:model.language];
            [weakSelf request:model.languageRequestStr];
            hidd(YES);
        };
    }
    
    if ([title isEqualToString:Localized(@"set_terms")]) {
        
        [self  policyClick:0];
        return;
    }
    if ([title isEqualToString:Localized(@"set_privacy")]) {
        [self  policyClick:1];
        return;
    }
    if ([title isEqualToString:Localized(@"set_accountCancel")]) {
        BRCancellationViewController *vc = [BRCancellationViewController new];
        [self.navigationController pushViewController:vc animated:YES];
        
        return;
    }
}

#pragma mark - SET UI --
- (void)setUI {
    BRNavView *top = [self br_createTop:Localized(@"set_setting")];
   
    self.tableView.frame  = CGRectMake(0, kSafeAreaTopHeight, kScreenWidth, kScreenHeight - kSafeAreaTopHeight - kSafeAreaBottomHeight - 82);
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BRTopTitleTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"BRTopTitleTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BRTitleTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"BRTitleTableViewCell"];
    
    UIView *head = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 22)];
    head.backgroundColor = UIColor.clearColor;
    self.tableView.tableHeaderView = head;
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    

    QMUIButton *logoutBtn = [BRToolsView br_btnBGImg:Localized(@"set_logout")];
    [self.view addSubview:logoutBtn];
    [logoutBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(52);
        make.width.mas_equalTo(kScreenWidth - 28);
        make.left.equalTo(self.view).offset(14);
        make.bottom.equalTo(self.view.mas_bottom).offset(- (15 + kSafeAreaBottomHeight));
    }];
    
    [logoutBtn addTarget:self action:@selector(logout) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.view bringSubviewToFront:top];
}

- (NSArray *)lists {

    return @[Localized(@"set_selectLanguage"),Localized(@"menu_version"),Localized(@"set_terms"),Localized(@"set_privacy"),Localized(@"set_accountCancel")];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
